#include <os.h>
#include "screen.h"
#include "nimg.h"
#include "gameloop.h"
#include "autorelease.h"
#include "text.h"
#include "optimized.h"
#include "objects.h"   
#include "file.h"

static nspire_screen_buffer* frameBuffer = NULL;
static FILE* file = NULL;
static int count = 1000;
int gameCrappyRandom();

int update() {
    if (isKeyPressed(KEY_NSPIRE_5)) return 1;
    
    char buffer[500];
    unsigned int rand = (unsigned int) gameCrappyRandom();
    sprintf(buffer, "Random number: %u", rand);
    screenBufferDrawString(10,10,buffer,0xF0,2,frameBuffer);
    
    
    if (file && count > 0) {
        sprintf(buffer, "%u\n", rand);
        fwrite(buffer, 1, strlen(buffer), file);
        screenBufferDrawString(10,26,"Wrote to file",0xF0,2,frameBuffer);
        count--;
    }
    
    
    return 0;
}

void draw() {
    screenBufferFlushToScreen(frameBuffer);
    screenBufferClear(255, frameBuffer);
}

int main() {
    frameBuffer = screenBufferAlloc(320, 240);
    screenBufferClear(0xFF, frameBuffer);
    file = fopen("/documents/scatter.tns","a");
    
    game_event_funcs_t funcs;
    funcs.init = NULL;
    funcs.update = update;
    funcs.draw = draw;
    funcs.finish = NULL;
    funcs.fps = NULL;
    
    gameLoopRun(&funcs, 500);
    gameAutoDrain();
    if (file) fclose(file);
    return 0;
}